package com.ruoyi.management.base.utils;

import lombok.extern.slf4j.Slf4j;


@Slf4j
public class HexUtils {


    // 其他现有方法...

    /**
     * 计算CRC-16校验值（Modbus RTU标准）
     *
     * @param data 输入字节数组
     * @return CRC-16校验值的字节数组（2字节）
     */
    public static byte[] calculateCRC(byte[] data) {
        int crc = 0xFFFF; // 初始值
        for (byte b : data) {
            crc ^= (b & 0xFF);
            for (int i = 0; i < 8; i++) {
                if ((crc & 0x0001) != 0) {
                    crc >>= 1;
                    crc ^= 0xA001;
                } else {
                    crc >>= 1;
                }
            }
        }
        return new byte[]{
                (byte) (crc & 0xFF),       // 低字节
                (byte) ((crc >> 8) & 0xFF) // 高字节
        };
    }

    // 验证十六进制字符串是否合法
    public static boolean isValidHex(String hex) {
        return hex.matches("[0-9a-fA-F]+");
    }

    // 十六进制字符串转字节数组
    public static byte[] hexToBytes(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return data;
    }

    // 字节数组转十六进制字符串
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }

    /**
     * 16进制字符串转换为Byte型数组16进制源字符串
     *
     * @param 16进制字符串
     * @return Byte类型数组
     */
    public static byte[] HexStringToByte(String hexString) {
        hexString = hexString.replace(" ", "");
        int len = hexString.length();
        if (len % 2 != 0)
            return null;
        byte[] bufD = new byte[len / 2];
        byte[] tmpBuf = hexString.getBytes();
        int i = 0, j = 0;
        for (i = 0; i < len; i++) {
            if (tmpBuf[i] >= 0x30 && tmpBuf[i] <= 0x39)
                tmpBuf[i] -= 0x30;
            else if (tmpBuf[i] >= 0x41 && tmpBuf[i] <= 0x46)
                tmpBuf[i] -= 0x37;
            else if (tmpBuf[i] >= 0x61 && tmpBuf[i] <= 0x66)
                tmpBuf[i] -= 0x57;
            else
                tmpBuf[i] = 0xF;
        }
        for (i = 0, j = 0; i < len; i += 2, j++) {
            bufD[j] = (byte) ((tmpBuf[i] << 4) | tmpBuf[i + 1]);
        }
        return bufD;

    }

 //将普通字符串转换为整数
     public static Integer StringToInt(String args) {
         Integer number = null; // 声明并初始化为 null
         try {
             // 使用 Integer.parseInt() 转换字符串为整数
             number = Integer.parseInt(args);
         } catch (NumberFormatException e) {
             log.debug("Invalid input: The string is not a valid integer.");

         }
         return number;
     }


}
